package njust.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import njust.dao.NeedsDao;
import njust.domain.Image;
import njust.domain.Needs;

public class NeedsDaoImpl extends HibernateDaoSupport implements NeedsDao {
	

	@Override
	public List<Needs> getNeedsByPage(final int pageSize, final int pageNow) {
		List list = new ArrayList();
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery("from Needs")
						.setFirstResult(pageNow * pageSize - pageSize)
						.setMaxResults(pageSize);
				query.setCacheable(true);
				List list1 = query.list();
				return list1;
			}
		});

		return list;
	}
	@Override
	public int pageTotle(int pageSize, int pageNow) {
		this.getHibernateTemplate().setCacheQueries(true);
		int i = this.getHibernateTemplate().find("from Needs").size();
		i = i % pageSize == 0 ? i / pageSize : i / pageSize + 1;
		return i;
	}
	
	
	@Override
	public List getNeedByUserId(int id) {
		// TODO Auto-generated method stub
		List list = new ArrayList();
		list = this.getHibernateTemplate()
				.find("from Needs where userid="+id+" order by Time desc ");
		return list;
	}

	@Override
	public boolean addNeeds(Needs needs) {
		this.getHibernateTemplate().save(needs);
		return true;
	}

	@Override
	public boolean deleteNeeds(int id) {
		Needs needs = (Needs) this.getHibernateTemplate().get(Needs.class, id);
		this.getHibernateTemplate().delete(needs);
		return true;
	}

	@Override
	public List getAllNeeds() {
		List list = new ArrayList();
		// this.getHibernateTemplate().setCacheQueries(true);
		list = this.getHibernateTemplate().find("from Needs order by Id desc");
		return list;
	}

	@Override
	public Needs getNeedsById(int id) {
		Needs needs = (Needs) this.getHibernateTemplate().get(Needs.class, id);
		return needs;
	}

}
